#coding:utf8
import logging
from flask import current_app, render_template, session, request, jsonify, g
from info import redis_store, constants
from info.models import User, News, Category
from info.utils.common import user_login_data
from info.utils.response_code import RET
from . import index_blu


#获取首页新闻列表数据
# 请求路径: /newslist
# 请求方式: GET
# 请求参数: cid,page,per_page
# 返回值: data数据
@index_blu.route('/newslist')
def get_news_list():
    """
    思路分析
    1.获取参数
    2.校验参数,转换整数类型
    3.查询数据,根据条件
    4.将新闻对象列表,转成字典列表
    5.返回
    :return:
    """
    # 1.获取参数
    cid = request.args.get("cid")
    page = request.args.get("page",1)
    per_page = request.args.get("per_page",10)

    # 2.校验参数,转换整数类型
    try:
        page = int(page)
        per_page = int(per_page)
    except Exception as e:
        current_app.logger.error(e)
        page = 1
        per_page = 10

    # 3.查询数据,根据条件
    try:

        #判断cid是否不等于1
        filters = []
        if cid != "1":
            filters.append(News.category_id == cid)

        #按照创建时间排序,第page页,每页per_page条,查不到不进行错误输出
        paginate = News.query.filter(*filters).order_by(News.create_time.desc()).paginate(page,per_page,False)
        #获取总页数,当前页,当前对象列表
        totalPage = paginate.pages
        currentPage = paginate.page
        items = paginate.items

    except Exception as e:
        current_app.logger.error(e)
        return jsonify(errno=RET.DBERR,errmsg="查询异常")

    # 4.将新闻对象列表,转成字典列表
    newsList = []
    for news in items:
        newsList.append(news.to_dict())

    # 5.返回
    return jsonify(errno=RET.OK,errmsg="查询成功",cid=cid,totalPage=totalPage,currentPage=currentPage,newsList=newsList)


@index_blu.route('/',methods=["GET","POST"])
@user_login_data
def hello_world():

    #取出session中的用户编号
    # user_id = session.get("user_id")
    #
    # #取出用户对象
    # user = None
    # if user_id:
    #     try:
    #         user = User.query.get(user_id)
    #     except Exception as e:
    #         current_app.logger.error(e)


    #处理热门新闻,查询前10条
    try:
        click_news = News.query.order_by(News.clicks.desc()).limit(constants.CLICK_RANK_MAX_NEWS).all()
    except Exception as e:
        current_app.logger.error(e)

    #将新闻对象列表,转成字典列表
    click_news_list = []
    for news in click_news:
        click_news_list.append(news.to_dict())

    #获取分类数据
    try:
        categories = Category.query.all()
    except Exception as e:
        current_app.logger.error(e)

    #将对象分类列表转成,字典列表
    categories_list = []
    for category in categories:
           categories_list.append(category.to_dict())


    #将用户的对象信息转成字典信息
    data = {
        "user_info":g.user.to_dict() if g.user else None,
        "click_news_list":click_news_list,
        "categories":categories_list
    }

    return render_template('news/index.html',data=data)


#每个网站都会发送请求/favicon.ico,去加载logo图片
#如果指定访问static中的内容, current_app.send_static_file(),自动寻找static中的内容,返回响应体对象
@index_blu.route('/favicon.ico')
def web_log():

    return current_app.send_static_file('news/favicon.ico')